﻿// Glitter
// glitter_xie@qq.com
// 2019/11/15
using System;
using System.Security.Claims;
using System.Text.Json;
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Validation;

namespace Cas
{
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        public virtual async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            //根据context.UserName和context.Password与数据库的数据做校验，判断是否合法
            if (context.UserName == "test1" && context.Password == "1")
            {

                context.Result = new GrantValidationResult(
                 subject: context.UserName,
                 authenticationMethod: "custom",
                 claims: GetUserClaims());
            }
            else
            {
                //验证失败
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
            }
        }

        //可以根据需要设置相应的Claim
        //例如：角色，权限列表等
        private Claim[] GetUserClaims()
        {
            return new Claim[]
            {
            new Claim("UserId", Guid.NewGuid().ToString()),
            new Claim("Role",JsonSerializer.Serialize(new {Role1= "role1",Role2="role2",Role3="role3" })),
            new Claim("Privilege",JsonSerializer.Serialize(
                new {
                    Privilege1 = new
                    {
                        Id = Guid.NewGuid(),
                        Privilege = "User.Add"
                    },
                    Privilege2 = new
                    {
                        Id = Guid.NewGuid(),
                        Privilege = "User.Edit"
                    },
                    Privilege3 = new
                    {
                        Id = Guid.NewGuid(),
                        Privilege = "User.Delete"
                    }
                }
                )
            )
            };
        }
    }
}
